package com.zrrd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.reggie.bean.Dish;
import com.zrrd.reggie.bean.DishDto;
import com.zrrd.reggie.bean.DishFlavor;
import com.zrrd.reggie.mapper.DishFlavorMapper;
import com.zrrd.reggie.mapper.DishMapper;
import com.zrrd.reggie.service.DishFlavorService;
import com.zrrd.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.event.WindowFocusListener;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    //注入口味mapper
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private DishMapper dishMapper;

    @Override
    //开始事务控制
    @Transactional
    public void saveDish(DishDto dto){


        log.info("执行添加菜品===>");

        //添加数据到菜品表
        this.save(dto);

        log.info("口味集合===>{}",dto.getFlavors());

        //获取dto中的口味列表
        List<DishFlavor> flavors = dto.getFlavors();
        //遍历集合
        for (DishFlavor flavor : flavors) {
            //设置口味所属的菜品id
            flavor.setDishId(dto.getId());
            //保存数据到口味表
            dishFlavorMapper.insert(flavor);
        }

    }

    //修改
    @Override
    @Transactional
    public void updateDish(DishDto dto){
        //更新dish的基本信息
        this.updateById(dto);

        //删除菜品对应的口味列表
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id",dto.getId());
        dishFlavorMapper.delete(wrapper);

        //获取dto中的口味列表
        List<DishFlavor> flavors = dto.getFlavors();
        //遍历集合
        for (DishFlavor flavor :flavors){
            //设置口味所属的菜品id
            flavor.setDishId(dto.getId());
            //保存数据到口味表
            dishFlavorMapper.insert(flavor);
        }
    }

    @Override
    @Transactional
    public void deleteDish(Long[] ids){
        //将id的数组转为集合
        List<Long> lish = Arrays.asList(ids);
        //批量删除
        this.removeByIds(lish);


        //遍历集合获取每个菜品id
        for (Long id : lish){
            QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
            wrapper.eq("dish_id",id);
            dishFlavorMapper.delete(wrapper);
        }
    }

    //停售
    @Override
    public void updateStatus0(Long[] ids){
        for (Long id : ids){
            Dish dish = dishMapper.selectById(id);
            dish.setStatus(0);
            dishMapper.updateById(dish);
        }
    }
}
